package com.liziyi0914.morearmor.effect;

import com.liziyi0914.morearmor.PlayerManager;
import com.liziyi0914.morearmor.Utils;
import com.liziyi0914.morearmor.event.Listener;
import com.liziyi0914.morearmor.event.entity.EntityDamageByEntityEvent;
import com.liziyi0914.morearmor.event.entity.EntityDamageEvent;
import net.minecraft.entity.LivingEntity;
import net.minecraft.entity.TntEntity;
import net.minecraft.item.Items;
import net.minecraft.server.network.ServerPlayerEntity;
import net.minecraft.server.world.ServerWorld;
import net.minecraft.world.World;

import java.util.HashMap;
import java.util.UUID;
import java.util.function.Predicate;

public class TntEffect extends AbstractEffect {

    HashMap<UUID, Long> record = new HashMap<>();

    @Listener
    public void onTick(EntityDamageByEntityEvent e) {
        LivingEntity livingEntity = e.getEntity();
        if (!predicateArmor().test(livingEntity)) {
            return;
        }
        final ServerPlayerEntity playerEntity = PlayerManager.get(livingEntity.getUuid());
        if (playerEntity == null) return;
        World world = playerEntity.getServerWorld();
        LivingEntity living = e.getDamager();
        long time = record.getOrDefault(playerEntity.getUuid(), 0L);
        if (System.currentTimeMillis() - time >= 1000) {
            record.put(playerEntity.getUuid(), System.currentTimeMillis());
            TntEntity tntEntity = new TntEntity(world, livingEntity.getX(), livingEntity.getY(), livingEntity.getZ(), playerEntity);
            tntEntity.setFuse(5);
            world.spawnEntity(tntEntity);
        }
    }

    @Listener
    public void onExplode(EntityDamageEvent e) {
        if (!e.getSource().isExplosive() || !predicateArmor().test(e.getEntity())) {
            return;
        }
        if (e.getEntity().getEntityWorld() instanceof ServerWorld) {
            e.setCanceled(true);
        }
    }

    @Override
    public Predicate<LivingEntity> predicateArmor() {
        return Utils.hasItemArmor(Items.TNT);
    }
}
